﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace DSUltimate.Parsers
{
    public class AmazonParser 
    {
        private WebClient client;
        private AmazonParserSettings settings;
        private HtmlDocument document;

        public AmazonParser(AmazonParserSettings set)
        {
            this.document = new HtmlDocument();
            this.client = new WebClient();
            this.settings = set; 
        }

        private string GetTitle(string Html)
        {
           
            document.LoadHtml(Html);
            HtmlNode title = document.GetElementbyId("productTitle");
            return title.InnerText;
         
        }
        private string GetBullets(string Html)
        {
            HtmlNode bulletPoints = document.GetElementbyId("feature-bullets");
            StringBuilder bullets = new StringBuilder();

            Regex li = new Regex("<li>[^<>]+<\\/li>"); //FIX

            MatchCollection bulletsCollection = li.Matches(bulletPoints.InnerHtml);
            if (bulletsCollection.Count < 2)
            {
                return RemoveEmptySpaces(bulletPoints.InnerText);//No Li structure
            }
            string itemToAdd;
            foreach (Match bullet in bulletsCollection)
            {
                itemToAdd = bullet.Value.Replace("<li>", String.Empty); //FIX
                itemToAdd = itemToAdd.Replace("</li>", String.Empty);
                bullets.AppendLine(RemoveEmptySpaces(itemToAdd));
            }
        
            return bullets.ToString();
        }
        private string GetDescription(string Html)
        {
            if (Html.IndexOf("iframeContent") > 0)
            {
                Regex r = new Regex("%[A-Z0-9]{2}");
                string descriptionBeggining = Html.Substring(Html.IndexOf("iframeContent"));
                descriptionBeggining = r.Replace(descriptionBeggining, " ");

                int start = descriptionBeggining.IndexOf("div class  productDescriptionWrapper") + 36;
                int len = descriptionBeggining.IndexOf("div class  emptyClear") - start;
                string content = descriptionBeggining.Substring(start, len);

                return RemoveEmptySpaces(RemoveHtmlTags(content));
            }
            else
            {
                return "No Item Description! Check Manualy to be sure.";
            }

        }
        private List<Image> GetImages(string Html)
        {
            int Errors = 0;
            Regex picRegEx = new Regex("\"http://ecx.images-amazon.com/images/I/[A-Za-z0-9%._-]+.jpg\"");
            List<Image> images = new List<Image>();
            MatchCollection allPicsCollection = picRegEx.Matches(Html);
            List<string> picsCollection = new List<string>();

            for (int j = 0; j < allPicsCollection.Count; j++)
            {
                if (allPicsCollection[j].Value.Contains("SL") || !settings.FilterImages)
                {
                    picsCollection.Add(allPicsCollection[j].Value);
                }
            }

            Image newPic;

            int i = 0;
            foreach (string pic in picsCollection)
            {          
                    string imagePath = pic.Substring(1, pic.Length - 2);
          
                        try
                        {                  
                            Stream stream = new MemoryStream(client.DownloadData(new Uri(imagePath)));                          
                            newPic = Image.FromStream(stream);
                                                     
                            Size s = newPic.Size;
                            if (s.Width > 300 && s.Height > 300)
                            {
                                images.Add(newPic);

                            }
                            i++;
                        }
                        catch (Exception)
                        {
                            Errors++;
                        }
         
            }

            if (Errors > 0)
            {
                System.Windows.Forms.MessageBox.Show(string.Format("{0} errors occured while downloading images!", Errors));
            }

            return images;
        }

        public AmazonItemDetailed GetAmazonItemDetailed(string link)
        {
            string Html = client.DownloadString(link);
            AmazonItemDetailed newAmazonItem = new AmazonItemDetailed();
            newAmazonItem.Link = link;
            newAmazonItem.Title = GetTitle(Html);
            newAmazonItem.BulletPoints = GetBullets(Html);
            newAmazonItem.ItemDescription = GetDescription(Html);
            newAmazonItem.Images = GetImages(Html);
            if (link.Contains(".co.uk"))
            {
                newAmazonItem.Site = "UK";
            }
            else if (link.Contains(".co.uk"))
            {
                newAmazonItem.Site = "USA";
            }


            return newAmazonItem;
        }






        public static string RemoveHtmlTags(string text)
        {
            string[] tags = { "html", "head", "body", "h1", "h2", "h3", "p", "br", "div","span" };
            string result = Regex.Replace(text, @"<[^>]*>", String.Empty);
            foreach (string tag in tags)
            {
                result = result.Replace(tag, String.Empty);
            }
            return result;
        }

        public static string RemoveEmptySpaces(string text)
        {
            Regex r = new Regex("(?:[^a-z0-9% ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
            string noCtrlChars = r.Replace(text, String.Empty);
            StringBuilder newText = new StringBuilder();
            for (int i = 0; i < noCtrlChars.Length - 1; i++)
            {
                if (noCtrlChars[i] == ' ')
                {
                    if (noCtrlChars[i + 1] != ' ')
                    {
                        newText.Append(noCtrlChars[i]);
                    }
                }
                else
                {
                    newText.Append(noCtrlChars[i]);
                }
            }
            return newText.ToString();

           
        }


    }
}
